package com.example.demofdfs.util;

import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.github.tobato.fastdfs.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.proto.storage.DownloadCallback;
import com.github.tobato.fastdfs.service.FastFileStorageClient;

@Component
public class FdfsUtil {

	@Autowired
	private FastFileStorageClient storageClient;


	public String upload(MultipartFile file) {
		try {
			return storageClient.uploadFile(
				file.getInputStream(), 
				file.getSize(), 
				FilenameUtils.getExtension(file.getOriginalFilename()), 
				null).getFullPath();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public void delete(String filepath) {
		storageClient.deleteFile(filepath);
	}
	
	public byte[] download(String filepath) {
		String groupName, path;
		int index = filepath.indexOf("/");
		groupName = filepath.substring(0, index);
		path = filepath.substring(index + 1, filepath.length());
		return storageClient.downloadFile(groupName, path, new FdfsCallback());
	}
	
	private static class FdfsCallback implements DownloadCallback<byte[]> {

		@Override
		public byte[] recv(InputStream ins) throws IOException {
			
			return IOUtils.toByteArray(ins);
		}
		
	}
}
